package com.cyh.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * Pipe的使用
 * */
public class PipeDemo01 {

    public static void main(String[] args) throws Exception {

       //1 创建Pipe
        Pipe pipe = Pipe.open();

        //2 获取sink通道
        Pipe.SinkChannel sinkChannel = pipe.sink();

        //3 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put("atgigu".getBytes());
        byteBuffer.flip();

        //4 写入数据
        sinkChannel.write(byteBuffer);

        //5 获取source通道
        Pipe.SourceChannel sourceChannel = pipe.source();

        //6 创建缓冲区， 读取数据
        byteBuffer.flip();
        int length = sourceChannel.read(byteBuffer);

        System.out.println(new String(byteBuffer.array(), 0, length));

        //关闭通道
        sourceChannel.close();
        sinkChannel.close();
    }
}
